<!--
 * @Author: zhang_wenjuan
 * @Date: 2021-05-19 16:44:45
 * @LastEditTime: 2021-08-02 09:56:06
 * @Description: 添加缺陷
-->

<template>
    <div id="addHiddenDanger_page">
        <!-- 顶部导航 -->
        <van-nav-bar :title="title" left-arrow @click-left="back" fixed>
            <van-icon class="scan" name="scan" slot="right" size="22" />
            <van-icon name="qr" slot="right" size="22" />
            <template slot="right">
                <div class="parent-circle">
                    <div class="child-circle"></div>
                </div>
            </template>
        </van-nav-bar>
        <!-- 选择区域 -->
        <div class="selectPart">
            <!-- 变电站名称 -->
            <!-- <van-field readonly required v-model="addData.substationName" placeholder="请选择（必选）" label="变电站名称" input-align="right" right-icon="arrow"
                @click="showSub=true" /> -->
            <van-field required readonly v-model="addData.substationName" placeholder="请选择（必选）" label="变电站名称："
                input-align="right" right-icon="arrow" />
            <!-- 设备名称 -->
            <van-field required readonly v-model="addData.deviceName" placeholder="请选择（必选）" label="设备名称："
                input-align="right" right-icon="arrow" @click="showdevice=true" />
            <!-- 缺陷部位 -->
            <van-field @click="openDefectLib" required readonly v-model="addData.defectPositionText"
                placeholder="请选择（必选）" label="缺陷部位：" input-align="right" right-icon="arrow" />
            <!-- 分类依据 -->
            <van-field @click="openDefectLib" required readonly v-model="addData.classificationStandardText"
                placeholder="请选择（必选）" label="分类依据：" input-align="right" right-icon="arrow" />
            <!-- 缺陷性质 -->
            <van-field @click="openDefectLib" readonly required v-model="addData.defectNatureText" placeholder="请选择（必选）"
                label="缺陷性质：" input-align="right" right-icon="arrow" />
            <!-- 缺陷描述 -->
            <van-field @click="openDefectLib" readonly required v-model="addData.defectDescText" placeholder="请选择（必选）"
                label="缺陷描述：" input-align="right" right-icon="arrow" />
            <!-- 发现人 -->
            <van-field @click="showFindPopup" readonly required v-model="addData.findUserName" placeholder="请选择（必选）"
                label="发现人：" input-align="right" right-icon="arrow" />
            <!-- 发现方式 -->
            <van-field @click="showGongXing=true" readonly required v-model="addData.findWay" placeholder="请选择（必选）"
                label="发现方式：" input-align="right" right-icon="arrow" />
            <!-- 发现时间 -->
            <van-field @click="findTimePopup=true" readonly required v-model="addData.findTime1" placeholder="请选择（必选）"
                label="发现时间：" input-align="right" right-icon="arrow" />
            <!-- 缺陷内容 -->
            <div class="descBox">
                <div>缺陷内容：</div>
                <van-field style="white-space:pre;" class="descField" v-model.trim="addData.defectContent" rows="2"
                    autosize type="textarea" maxlength="256" placeholder="请输入缺陷内容" show-word-limit />
            </div>
            <div class="descBox">
                <div>附件：</div>
                <div class="imgItemBox">
                    <div class="fileItem" v-for="(item,i) in fileList" :key="i">
                        <img class="itemImg" :src="item.content" alt="" srcset="">
                        <div class="del">
                            <van-icon name="close" color="#F56C6C" size="24" @click='delImg(i)' />
                        </div>
                    </div>
                    <img src="../../images/addTestData.png" @click="uploadShow=true">
                </div>
            </div>
        </div>
        <!-- 下拉框区域 -->
        <!-- 变电站下拉弹窗 -->
        <van-popup v-model="showSub" position="bottom">
            <van-picker show-toolbar :columns="subArr" @confirm="confirmsub" @cancel="showSub = false"
                value-key="subName" />
        </van-popup>
        <!-- 缺陷设备下拉弹窗 -->
        <!-- <van-popup v-model="showdevice" position="bottom">
            <van-picker show-toolbar :columns="deviceArr" @confirm="confirmdevice" @cancel="showdevice = false"
                value-key="deviceName" />
        </van-popup> -->
        <!-- 设备类型下拉弹窗 -->
        <van-popup v-model="showdeviceType" position="bottom">
            <van-picker show-toolbar :columns="deviceTypeArr" @confirm="confirmdeviceType"
                @cancel="showdeviceType = false" value-key="deviceTypeName" />
        </van-popup>
        <!-- 发现时间下拉弹窗(结束) -->
        <van-popup v-model="findTimePopup" position="bottom">
            <van-datetime-picker type="datetime" @confirm="confirmTime()" title="选择发现时间" v-model="findTimeCopy"
                :min-date="minDate" :formatter="formatter" :max-date="maxDate" @cancel="findTimePopup = false" />
        </van-popup>
        <!-- 选择审核人下拉弹窗 -->
        <van-popup v-model="selectExamUser" :style="{ height: '30%' }" position="bottom">
            <div class="selectUser">
                <van-nav-bar title="选择审核人" @click-left="selectExamUser=false" fixed>
                    <template slot="left">
                        <div class="">
                            <div class="header_fs" @click="cencel">取消</div>
                        </div>
                    </template>
                    <template slot="right">
                        <div class="">
                            <div class="header_fs" @click='sure'>确定</div>
                        </div>
                    </template>
                </van-nav-bar>
                <div class="listPart">
                    <van-row class="bg_4dbfae header search_header" type="flex" justify='space-around'>
                        <van-search v-model.trim="searchUserName" @clear="cancelSelUser" @input="focusSelUser"
                            placeholder="请输入搜索关键词" />
                    </van-row>
                    <div class="list_item">
                        <van-radio-group v-model="radio">
                            <van-cell-group>
                                <van-cell v-for="(item, index) in findUserArr" clickable :key="index"
                                    :title="item.userName" clickable @click="toggle(index)">
                                    <template #right-icon>
                                        <van-radio :name="index" />
                                    </template>
                                </van-cell>
                            </van-cell-group>
                        </van-radio-group>
                    </div>

                </div>
            </div>
        </van-popup>
        <!-- 选择发现人下拉弹窗 -->
        <van-popup v-model="findUserShow" :style="{ height: '30%' }" position="bottom">
            <div class="selectUser">
                <van-nav-bar title="选择发现人" @click-left="findUserShow=false" fixed>
                    <template slot="left">
                        <div class="">
                            <div class="header_fs" @click="findUserShow=false">取消</div>
                        </div>
                    </template>
                    <template slot="right">
                        <div class="">
                            <div class="header_fs" @click='confirmfindUser'>确定</div>
                        </div>
                    </template>
                </van-nav-bar>
                <div class="listPart">
                    <van-row class="bg_4dbfae header search_header" type="flex" justify='space-around'>
                        <van-search v-model.trim="searchUserName" @clear="cancelSelUser" @input="focusSelUser"
                            placeholder="请输入搜索关键词" />
                    </van-row>
                    <div class="list_item">
                        <van-checkbox-group v-model="result">
                            <van-cell-group>
                                <van-cell v-for="(item, index) in findUserArr" clickable :key="index"
                                    :title="item.userName" clickable @click="toggleFindUser(index,item)">
                                    <template #right-icon style="float: right;">
                                        <van-checkbox :name="item" ref="checkboxes" />
                                    </template>
                                </van-cell>
                            </van-cell-group>
                        </van-checkbox-group>
                    </div>

                </div>
            </div>
        </van-popup>
        <!-- 选择设备下拉弹窗 -->
        <van-popup v-model="showdevice" :style="{ height: '30%' }" position="bottom">
            <div class="selectUser">
                <van-nav-bar title="选择设备名称" @click-left="showdevice=false" fixed>
                    <template slot="left">
                        <div class="">
                            <div class="header_fs" @click="showdevice = false">取消</div>
                        </div>
                    </template>
                    <template slot="right">
                        <div class="">
                            <div class="header_fs" @click='showdevice = false'>确定</div>
                        </div>
                    </template>
                </van-nav-bar>
                <div class="listPart">
                    <van-row class="bg_4dbfae header search_header" type="flex" justify='space-around'>
                        <van-search v-model.trim="deviceName" @clear="cancel" @input="focus" placeholder="请输入查询内容" />
                    </van-row>
                    <div class="list_item">
                        <van-cell style="text-align: center;" v-for="(item, index) in deviceArr" clickable :key="index"
                            :title="item.deviceName" clickable @click="confirmdevice(item)">
                        </van-cell>
                    </div>
                </div>
            </div>
        </van-popup>
        <!-- 选择发现方式下拉弹窗 -->
        <van-popup v-model="showGongXing" :style="{ height: '30%' }" position="bottom">
            <div class="selectUser">
                <van-nav-bar title="发现方式" @click-left="showdevice=false" fixed>
                </van-nav-bar>
                <div class="listPart">
                    <div class="list_item">
                        <van-cell style="text-align: center;" v-for="(item, index) in findModeArr" clickable
                            :key="index" :title="item" clickable @click="confirmGongXing(item)">
                        </van-cell>
                    </div>
                </div>
            </div>
        </van-popup>
        <van-popup v-model="uploadShow" :style="{ height: '10%' }" position="bottom">
            <div class="selectFile">
                <div class="photo">
                    <img src="../../images/photo.png" @click="photo">
                    <div>开始拍照</div>
                </div>
                <div class="selectImg">
                    <van-uploader class="selectfile" :after-read="afterRead">
                        <img src="../../images/selectFile.png" style="width: 3rem;
                        margin-left: 5rem;
                        margin-top: -0.7rem;">
                        <div style="margin-left: 4.5rem;">选择文件</div>
                    </van-uploader>
                </div>
            </div>
        </van-popup>
        <!-- 底部按钮区域 -->
        <div class="footPart">
            <van-button size="small" @click="sumbit('save')">保存</van-button>
            <van-button class="sureBtn" size="small" @click="sumbitExam()">提交</van-button>
        </div>
        <defect-library ref="defectLib" :defectLibShow='defectLibShow' @close="onClose"
            :deviceTypeId='addData.deviceType'></defect-library>
    </div>
</template>
<script type="text/javascript">
    import Utils from '@/utils/util'
    const PinyinEngine = require('pinyin-engine');
    import DefectLibrary from "./DefectLibrary.vue"
    import { getSubstationList, getDeviceAndBayForApp } from "../../api/common"
    import { getUserList, addDefect, uploadFile, downLoadFileUrl } from "../../api/defect"
    export default {
        name: "defectList",
        components: {
            DefectLibrary
        },
        data() {
            return {
                userInfo: JSON.parse(localStorage.getItem('userInfo')),
                showSub: false,// 是否显示选择变电站下拉弹窗
                showdeviceType: false,// 是否显示选择设备下拉弹窗
                showdevice: false,// 是否显示选择设备下拉弹窗
                showFenji: false,// 是否显示隐患分级下拉弹窗
                showFenlei: false,// 是否显示隐患分类下拉弹窗
                showHiddenDangerType: false,// 是否显示隐患类型下拉弹窗
                showSource: false,// 是否显示隐患来源下拉弹窗
                showGongXing: false,// 是否显示共性隐患下拉弹窗
                showMeasure: false,// 是否显示拟采取措施下拉弹窗
                findUserShow: false,// 是否显示发现人下拉弹窗
                selectExamUser: false,// 是否显示发现人下拉弹窗
                defectLibShow: false,// 选择缺陷库弹窗
                uploadShow: false,// 上传附件弹窗
                findTimePopup: false,// 选择时间弹窗
                findTimeCopy: new Date(),// 发现时间未处理的
                pinyinEngineByShow: null,
                pinyinEngineByUser: null,
                fileList: [],//变电站下拉列表
                subArr: [],//变电站下拉列表
                deviceTypeArr: [],//设备下拉列表
                deviceArr: [],//设备下拉列表
                findModeArr: ['人工巡视', '机器人巡视', '无人机巡视', '视频摄像头'],//巡视方式下拉列表
                findUserArr: [],//发现人下拉列表
                addData: {
                    "attachmentList": [],//附件
                    "auditorList": [],// 文件名
                    "classificationStandard": "",// 分类依据id
                    "classificationStandardText": "",// 分类依据text
                    "defectContent": "",// 缺陷内容
                    "defectDesc": "",// 缺陷描述
                    "defectDescText": "",// 缺陷描述
                    "defectId": "",// 缺陷id
                    "defectNature": "",// 缺陷性质
                    "defectNatureText": "",// 缺陷性质
                    "defectPosition": "",// 缺陷部位
                    "defectPositionText": "",// 缺陷部位
                    "deviceId": "",// 设备id
                    "deviceName": "",// 设备名称
                    "deviceType": "",// 设备类型id
                    "deviceTypeName": "",// 设备类型
                    "findTime": "",// 发现人时间
                    "findWay": "",// 发现方式
                    "findUserId": "",// 发现人id
                    "findUserName": "",// 发现人名字
                    "inspectTaskId": "",// 检修任务id
                    "roleCode": "",
                    "substationId": "",// 变电站id
                    "substationName": "",// 变电站名称
                    "substationRfid": "010020000000000025287847",// 变电站rfid
                    "userId": "",// 登录人id
                },
                list: ['a', 'b'],
                radio: null,
                title: '',
                deviceName: '',// 设备名称模糊查询
                result: [],
                searchUserName: '',// 查询人的姓名
                minDate: new Date(),
                maxDate: new Date(2080, 10, 1),
                result: [],// 发现人
                userNameArr: [],// 发现人名称数组
                userIdArr: [],// 发现人id数据
            }
        },
        created() {
            this.getDetailData()
            this.getDeviceAndBayForApp()// 获取设备和间隔
            this.getUserList()// 获取班组人员

        },
        methods: {
            // 拼音搜索清空
            cancel() {
                this.deviceArr = this.pinyinEngineByShow.query("")
            },
            // 拼音搜索执行
            focus() {
                this.deviceArr = this.pinyinEngineByShow.query(this.deviceName)
            },
            //日期格式
            formatter(type, val) {
                if (type === 'year') {
                    return val + '年';
                }
                if (type === 'month') {
                    return val + '月';
                }
                if (type === 'day') {
                    return val + '日';
                }
                if (type === 'hour') {
                    return val + '时';
                }
                if (type === 'minute') {
                    return val + '分';
                }
                return val;
            },
            /**
             * 返回
             */
            back() {
                if (this.$route.query.params && this.$route.query.params.taskInfo) {
                    this.$router.push({
                        name: "executeIndex",
                        params: {
                            taskInfo: this.$route.query.params.taskInfo
                        }
                    })
                } else {
                    this.$router.go(-1)
                }

            },

            /**
             * @description: 打开选择发现人弹窗
             * @param {*}
             * @return {*}
             */
            showFindPopup() {
                for (let i = 0; i < this.findUserArr.length; i++) {
                    for (let j = 0; j < this.userIdArr.length; j++) {
                        if (this.findUserArr[i].userId == this.userIdArr[j]) {
                            this.findUserShow = true
                            // 选中已有发现人
                            setTimeout(() => {
                                this.toggleFindUser(i, this.findUserArr[i])
                            }, 500);
                        } else {
                            this.findUserShow = true
                        }
                    }

                }
            },

            /**
             * @description:选择发现人 
             * @param {*} i
             * @return {*}
             */
            toggleFindUser(i, item) {
                this.$refs.checkboxes[i].toggle();
                item.checked = !item.checked
            },


            /**
             * @description: 获取详情数据
             * @param {*}
             * @return {*}
             */
            getDetailData() {
                var self = this
                // 判断是否有缺陷id  没有就是新增   有就是修改
                if (Utils.baseUtil.isEmptyString(this.$route.query.params.defectId)) {
                    // 判断是否有巡视任务信息  有就是从巡视任务跳过来的
                    if (this.$route.query.params.taskInfo) {
                        this.addData.inspectTaskId = this.$route.query.params.taskInfo.id;// 巡视任务id
                        this.addData.deviceId = this.$route.query.params.deviceInfo.deviceId;// 设备id
                        this.addData.deviceName = this.$route.query.params.deviceInfo.deviceName;// 设备名称
                        this.addData.deviceTypeId = this.$route.query.params.deviceInfo.deviceTypeId;// 设备类型id
                        this.addData.deviceTypeName = this.$route.query.params.deviceInfo.deviceTypeName;// 设备类型名称
                    }
                    this.addData.substationId = this.$route.query.params.subId// 变电站id
                    this.addData.substationName = this.$route.query.params.subName// 变电站名称
                    this.addData.findWay = "人工方式"// 发现方式
                    this.title = "添加缺陷"// 弹窗名称
                    this.addData.findUserId = this.userInfo.userId// 发现人id
                    this.addData.findUserName = this.userInfo.userName// 发现人名称 用于显示
                    this.userIdArr.push(this.userInfo.userId)// 发现人id
                    this.userNameArr.push(this.userInfo.userName) // 发现人名称  用于提交
                } else {
                    // 详情数据
                    this.addData = this.$route.query.params
                    // 格式化发现时间
                    this.addData.findTime1 = Utils.DateUtil.getFormatDateByLong(this.addData.findTime, 'yyyy-MM-dd hh:mm')
                    this.title = "修改缺陷"// 窗口名称
                    var arr = this.addData.attachmentList// 附件
                    //如果有附件  处理附件
                    if (arr.length > 0) {
                        for (let i = 0; i < arr.length; i++) {
                            // 下载附件并显示
                            downLoadFileUrl({
                                "fileUuid": arr[i].attachmentUuid,
                                "type": "0"
                            }).then(res => {
                                self.fileList.push({ content: res.url, uuid: arr[i].attachmentUuid })
                            }).catch(err => {
                                console.log(err);
                            })
                        }
                    }
                }
            },
            /**
             * @description: 开始拍照
             * @param {*}
             * @return {*}
             */
            photo() {
                this.$toast("暂无安卓支持")
            },

            /**
             * @description: 删除附件
             * @param {*} i
             * @return {*}
             */
            delImg(i) {
                // 如果删除的是已存在的文件
                if (!Utils.baseUtil.isEmptyString(this.fileList[i].uuid)) {
                    for (let j = 0; j < this.addData.attachmentList.length; j++) {
                        // 匹配uuid所在的下标
                        if (this.addData.attachmentList[j].attachmentUuid == this.fileList[i].uuid) {
                            this.addData.attachmentList.splice(j, 1)
                        }
                    }
                }
                this.fileList.splice(i, 1)
            },
            /**
             * @description: 选择文件
             * @param {*} file
             * @param {*} detail
             * @return {*}
             */
            afterRead(file, detail) {
                this.fileList.push(file)
                this.uploadShow = false
            },

            /**
             * @description: 审核人员选择
             * @param {*}
             * @return {*}
             */
            toggle(i) {
                this.$nextTick(() => {
                    // 全部置为未选中
                    for (let j = 0; j < this.findUserArr.length; j++) {
                        this.findUserArr[j].checked = false
                    }
                    // 选中当前选中
                    this.findUserArr[i].checked = true
                    this.radio = i
                })

            },
            /**
            * @description: 获取班组人员列表
            * @param {*}
            * @return {*}
            */
            getUserList() {
                var self = this
                var params = {
                    "roleCode": "string",
                    "orgId": this.userInfo.orgId,
                    "userId": this.userInfo.userId,
                    "keyWord": this.searchUserName
                }
                getUserList(params).then(res => {
                    if (res.success) {
                        self.findUserArr = res.data
                        // 全部置为未选中
                        self.findUserArr.forEach(v => {
                            v.checked = false
                        });
                        // 初始化模糊搜索
                        self.pinyinEngineByUser = new PinyinEngine(self.findUserArr, ["userName", "userId"])
                    } else {
                        // 未查询到  置空
                        self.findUserArr = []
                    }
                }).catch(err => {
                    // 查询失败  置空
                    self.findUserArr = []
                })
            },

            // 模糊查询取消
            cancelSelUser() {
                this.findUserArr = this.pinyinEngineByUser.query("")
            },
            // 模糊查询执行
            focusSelUser() {
                this.findUserArr = this.pinyinEngineByUser.query(this.searchUserName)
            },

            /**
             * @description: 打开缺陷库
             * @param {*}
             * @return {*}
             */
            openDefectLib() {
                if (Utils.baseUtil.isEmptyString(this.addData.deviceType)) {
                    this.$toast("请选择设备！")
                    return
                }
                this.$refs.defectLib.defectLibList = []
                // 执行获取缺陷库
                this.$refs.defectLib.getDefectDicInfo()
                this.defectLibShow = true
            },

            /**
             * @description: 选择缺陷库关闭
             * @param {*}
             * @return {*}
             */
            onClose(val) {
                // 这里赋值缺陷库
                if (!Utils.baseUtil.isEmptyString(val)) {
                    // 缺陷部位
                    this.addData.defectPosition = val.defectPosition
                    this.addData.defectPositionText = val.defectPositionText
                    // 分类依据
                    this.addData.classificationStandard = val.classificationStandard
                    this.addData.classificationStandardText = val.classificationStandardText
                    // 缺陷性质
                    this.addData.defectNature = val.defectNature
                    this.addData.defectNatureText = val.defectNatureText
                    // 缺陷描述
                    this.addData.defectDesc = val.defectDescCode
                    this.addData.defectDescText = val.defectDesc
                }
                // 缺陷库窗口关闭
                this.defectLibShow = false
            },

            /**
             * @description: 确定选择发现时间
             * @param {*}
             * @return {*}
             */
            confirmTime() {
                // 发现时间格式化 用于显示
                this.addData.findTime1 = Utils.DateUtil.getFormatDateByLong(this.findTimeCopy, 'yyyy-MM-dd hh:mm')
                this.addData.findTime = this.findTimeCopy// 发现时间
                this.findTimePopup = false// 选择发现时间窗口关闭
            },

            /**
             * @description: 确定选择变电站
             * @param {String} val 变电站
             */
            confirmsub(val) {
                this.addData.substationId = val.id// 变电站id
                this.getDeviceAndBayForApp()// 获取设备和间隔
                this.addData.substationName = val.subName// 变电站名称
                this.showSub = false// 选中变电站窗口关闭
            },
            /**
             * @description: 确定选择设备类型
             * @param {String} val 设备类型
             */
            confirmdeviceType(val) {
                this.addData.deviceTypeId = val.deviceTypeId// 设备类型id
                this.showdeviceType = false// 选择设备类型窗口关闭
            },
            /**
             * @description: 确定选择设备名称
             * @param {String} val 设备名称
             */
            confirmdevice(val) {
                if (Utils.baseUtil.isEmptyString(val)) {
                    this.$toast("请正确选择设备名称")
                } else {
                    this.addData.deviceId = val.deviceId// 设备id
                    this.addData.deviceName = val.deviceName// 设备名称
                    this.addData.deviceTypeName = val.deviceTypeName// 设备类型名称
                    this.addData.deviceType = val.deviceTypeId// 设备类型id
                    this.showdevice = false// 选择设备窗口关闭
                }
            },

            /**
             * @description: 确定选择隐患类型
             * @param {String} val 隐患类型
             */
            confirmHiddenDangerType(val) {
                this.showHiddenDangerType = false
            },
            /**
             * @description: 确定选择巡视方式
             * @param {String} val 巡视方式
             */
            confirmGongXing(val) {
                this.addData.findWay = val
                this.showGongXing = false
            },
            /**
             * @description: 确定选择发现人
             * @param 
             */
            confirmfindUser() {
                let flag = 0
                this.userNameArr = []
                this.userIdArr = []
                this.findUserArr.forEach(v => {
                    // 如果选中
                    if (v.checked) {
                        flag++
                        this.userNameArr.push(v.userName)
                        this.userIdArr.push(v.userId)
                    }
                });
                // flag==0  没有选中
                if (flag == 0) {
                    this.$toast("请选择发现人！")
                } else {
                    // 拼接
                    this.addData.findUserId = this.userIdArr.join(",")
                    this.addData.findUserName = this.userNameArr.join(",")
                    this.findUserShow = false
                }
            },

            /**
             * @description: 提交按钮
             * @param {*}
             * @return {*}
             */
            sumbitExam() {
                if (Utils.baseUtil.isEmptyString(this.addData.substationName)) {
                    return this.$toast("请选择变电站！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.deviceName)) {
                    return this.$toast("请选择设备名称！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.defectPositionText)) {
                    return this.$toast("请选择缺陷部位！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.findUserName)) {
                    return this.$toast("请选择发现人！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.findWay)) {
                    return this.$toast("请选择发现方式！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.findTime)) {
                    return this.$toast("请选择发现时间！");
                }
                // // 如果有审核人  
                if (this.addData.auditorList.length > 0) {
                    for (let i = 0; i < this.findUserArr.length; i++) {
                        if (this.addData.auditorList[0].auditorId == this.findUserArr[i].userId) {
                            this.toggle(i)//回显
                        }
                    }
                }
                this.selectExamUser = true
            },

            /**
             * @description: 选择审核人确定 并提交
             * @param {*}
             * @return {*}
             */
            sure() {
                var arr = []
                this.findUserArr.forEach(v => {
                    if (v.checked) {
                        arr.push({
                            "auditorId": v.userId,
                            "auditorName": v.userName
                        })
                    }
                });
                this.searchUserName = ''
                this.getUserList()// 重新获取人员列表
                this.addData.auditorList = arr
                this.sumbit('submit')// 提交
            },

            /**
             * @description: 取消选择人员
             * @param {*}
             * @return {*}
             */
            cencel() {
                this.selectExamUser = false// 选择人员窗口关闭
                this.searchUserName = ''// 模糊查询内容清空
                this.getUserList()// 重新获取人员列表
            },

            /**
             * @description: 提交
             */
            sumbit(type) {
                if (type == "save") {// 保存
                    this.addData.auditorList = []
                }
                if (Utils.baseUtil.isEmptyString(this.addData.substationName)) {
                    return this.$toast("请选择变电站！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.deviceName)) {
                    return this.$toast("请选择设备名称！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.defectPositionText)) {
                    return this.$toast("请选择缺陷部位！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.findUserName)) {
                    return this.$toast("请选择发现人！");
                }
                if (Utils.baseUtil.isEmptyString(this.addData.findWay)) {
                    return this.$toast("请选择发现方式！");
                }
                var self = this
                if (Utils.baseUtil.isEmptyString(this.addData.defectId)) {
                    this.$toast.loading({
                        duration: 0,//展示时长 0不会消失
                        message: "正在新增...",
                        forbidClick: true,//是否禁止背景点击
                        overlay: true//是否显示背景遮罩层
                    })
                } else {
                    this.$toast.loading({
                        duration: 0,//展示时长 0不会消失
                        message: "正在修改...",
                        forbidClick: true,//是否禁止背景点击
                        overlay: true//是否显示背景遮罩层
                    })
                }
                this.addData.userId = this.userInfo.userId
                var fileList = []
                if (self.fileList.length > 0) {
                    // 去除已存在的文件
                    for (let k = 0; k < self.fileList.length; k++) {
                        if (!Utils.baseUtil.isEmptyString(this.fileList[k].uuid)) {
                            this.fileList.splice(k, 1)
                        }
                    }
                    // 上传新文件
                    for (let i = 0; i < self.fileList.length; i++) {
                        var formData = new FormData;
                        formData.append("file", self.fileList[i].file) //文件流
                        fileList.push({
                            userId: self.userInfo.userId,
                            type: "0",
                            roleCode: "",
                            foreignKey: "",
                            formData: formData
                        })
                    }
                }
                for (let i = 0; i < self.addData.attachmentList.length; i++) {
                    if (self.addData.attachmentList[i] == null) {
                        self.addData.attachmentList.splice(i, 1)
                    } else {
                        self.addData.attachmentList[i].uuid = self.addData.attachmentList[i].attachmentUuid
                    }
                }
                var uuid = []
                // 如果有附件
                if (fileList.length > 0) {
                    for (let j = 0; j < fileList.length; j++) {
                        // 上传文件
                        uploadFile(fileList[j].formData).then(res => {
                            uuid.push(res.data)
                            if (uuid.length == fileList.length) {
                                // 拼接uuid
                                self.addData.attachmentList = self.addData.attachmentList.concat(uuid)
                                addDefect(self.addData).then(res => {
                                    if (res.success) {
                                        self.$toast.success("新增缺陷成功")
                                    } else {
                                        self.$toast("新增缺陷失败")
                                    }
                                    // 如果来自巡视  则返回巡视
                                    if (self.$route.query.params && self.$route.query.params.taskInfo) {
                                        self.$router.push({
                                            name: "executeIndex",
                                            params: {
                                                taskInfo: self.$route.query.params.taskInfo
                                            }
                                        })
                                    } else {
                                        // 否则返回缺陷列表
                                        self.$router.push({
                                            name: "DefectList"
                                        })
                                    }
                                    self.$toast.clear()
                                }).catch(err => {
                                    self.$toast.clear()
                                    self.$toast("新增缺陷失败")
                                })
                            }
                        }).catch(err => {
                            self.$toast("新增缺陷失败")
                            self.$toast.clear()
                        })
                    }

                } else {// 如果没有附件
                    addDefect(this.addData).then(function (res) {
                        self.$toast.clear()
                        if (res.success) {
                            self.$toast.success("新增缺陷成功")
                            // 如果来自巡视  则返回巡视
                            if (self.$route.query.params && self.$route.query.params.taskInfo) {
                                self.$router.push({
                                    name: "executeIndex",
                                    params: {
                                        taskInfo: self.$route.query.params.taskInfo
                                    }
                                })
                            } else {
                                // 否则返回缺陷列表
                                self.$router.push({
                                    name: "DefectList"
                                })
                            }
                        }
                    }).catch(err => {
                        self.$toast.clear()
                    });
                }
            },

            /**
             * @description: 获取变电站
             * @param {*}
             * @return {*}
             */
            getSubstationList() {
                var self = this
                var params = {
                    "keyword": "",
                    "roleCode": "",
                    "teamId": "11000007558700",
                    "userId": "915142429"
                }
                getSubstationList(params).then(res => {
                    if (res.success) {
                        self.subArr = res.data
                    } else {
                        self.subArr = []
                    }
                }).catch(err => {
                    self.subArr = []
                })
            },
            /**
             * @description: 获取设备类型
             * @param {*}
             * @return {*}
             */
            getDeviceAndBayForApp() {
                var self = this
                // 非法字符
                var regExp = /[@#\$%\^&\*\!\！\(\)\（\）\……\￥\&\_\-\——\=\+]+/g
                if (regExp.test(this.deviceName)) {
                    this.$toast("查询内容含非法字符")
                    return
                }
                var params = {
                    "roleCode": "",
                    "substationId": this.addData.substationId,
                    "deviceName": this.deviceName,
                    "userId": this.userInfo.userId
                }
                getDeviceAndBayForApp(params).then(res => {
                    if (res.success) {
                        var deviceArrCopy = res.data
                        // 去除间隔
                        for (let i = 0; i < deviceArrCopy.length; i++) {
                            for (let j = 0; j < deviceArrCopy[i].deviceList.length; j++) {
                                self.deviceArr.push(deviceArrCopy[i].deviceList[j])
                            }
                        }
                        // 模糊搜索初始化
                        self.pinyinEngineByShow = new PinyinEngine(self.deviceArr, ["deviceName", "deviceId"])
                    } else {
                        self.deviceArr = []
                    }
                }).catch(err => {
                    self.deviceArr = []
                })
            }
        },
        watch: {
            findUserShow(val) {
                if (!val) {
                    this.searchUserName = ""
                    this.getUserList()
                }
            }
        }
    }
</script>
<style scoped>
    #addHiddenDanger_page {
        width: 100%;
        height: 100%;
        padding-bottom: 0;
        background: #fff;
    }

    .van-nav-bar {
        background: #17b49b;
    }

    .van-nav-bar /deep/ .van-icon {
        color: #fff;
        font-size: 22px;
    }

    .scan {
        margin-right: 10px;
    }

    .van-nav-bar /deep/ .van-nav-bar__title {
        color: #fff;
        font-size: 18px;
    }

    .van-nav-bar /deep/ .van-button {
        background: #fff;
        color: #17b49b;
        width: 60px;
        border-radius: 4px;
    }

    .kong {
        width: 100%;
        height: 46px;
    }

    /* 选择区域 */
    .selectPart {
        height: calc(100% - 96px);
        overflow-y: auto;
    }

    /* 缺陷描述区域 */
    .descBox {
        /* width: 100vw; */
        padding: 0 16px;
        color: #646566;
        font-size: 14px;
        margin-top: 20px;
    }

    .descBox .descField {
        border: 1px solid #eee;
        margin-top: 10px;
    }

    /* 底部按钮区域 */
    .footPart {
        width: 100%;
        height: 50px;
        position: fixed;
        bottom: 0;
        left: 0;
        border-top: 1px solid #efefef;
        background: #fff;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .footPart .van-button {
        width: 100px;
        margin: 0 10px;
        border-radius: 5px;
    }

    .sureBtn {
        background: #17b49b;
        color: #fff;
    }

    .selectUser {
        width: 100%;
        height: 100%;

    }

    .header_fs {
        font-size: 1.125rem !important;
    }

    .van-nav-bar--fixed {
        position: unset;
    }

    .van-search {
        /* margin-top: 3rem; */
        width: 100%;
        border-radius: 25px !important;
        background-color: #fff !important;
        border: none !important;
        height: 2.5rem !important;

    }

    .van-search__content {
        border-radius: 25px !important;
    }

    .van-radio {
        float: right;
    }

    .van-cell__title,
    .van-cell__value {
        font-style: 16px;
    }

    .selectFile {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .selectFile>div {
        height: 3rem;
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }

    .selectFile>div>img {
        height: 100%;
    }

    .selectImg {
        border-left: 1px solid #cccccc;
        position: relative;
    }

    .selectfile {
        position: absolute;
        top: 0;
        left: 0;
    }

    .itemImg {
        width: 80px;
        height: 78px;
        /* margin-left: 10px; */
    }

    .fileItem {
        width: 80px;
        height: 78px;
        margin-left: 10px;
        position: relative;
    }

    .imgItemBox {
        /* width: 100vw; */
        display: flex;
        flex-wrap: wrap;
    }

    .del {
        position: absolute;
        top: 0;
        right: 0;
    }

    .list_item {
        height: 9rem;
        overflow-y: auto;
    }

    .list_item /deep/ .van-cell {
        border-bottom: 1px solid rgba(229, 229, 229, 1);
    }

    .van-checkbox {
        float: right;
    }
</style>